package com.example.gateway.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Map;

/**
 * 描述
 *
 * @author Huzz
 * @create 2022-07-15 15:24
 */
public class MonoUtil {

    public static Mono<Void> noAuth(ServerWebExchange exchange, Map<String, Object> data) {
        try {
            ServerHttpResponse response = exchange.getResponse();
            // 将信息转换为 JSON
            ObjectMapper objectMapper = new ObjectMapper();
            byte[] bytes = objectMapper.writeValueAsBytes(data);

            // 输出错误信息到页面
            DataBuffer buffer = response.bufferFactory().wrap(bytes);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
            return response.writeWith(Mono.just(buffer));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            // JSON格式化失败
        }
        return null;
    }
}
